// ============================================================================
// 关键字窗口管理前端服务
// ============================================================================

import { ipcService } from './ipc-service'
import { logger } from '../utils/logger'

/**
 * 关键字窗口摘要
 */
export interface KeywordWindowSummary {
  keyword: string
  windowSize: string
  totalPosts: number
  hasMoreHistory: boolean
  lastUpdate: string
}

/**
 * 关键字窗口详情
 */
export interface KeywordWindowDetails extends KeywordWindowSummary {
  details: {
    startTime?: Date
    endTime?: Date
    hasMoreHistory: boolean
    lastHistoryCrawlAt?: Date
    totalPostsCrawled: number
    latestPostsCrawled: number
    historyPostsCrawled: number
    createdAt: Date
    updatedAt: Date
  }
}

/**
 * 关键字窗口更新参数
 */
export interface KeywordWindowUpdateParams {
  hasMoreHistory?: boolean
  startTime?: Date
  endTime?: Date
}

/**
 * 时间范围
 */
export interface TimeRanges {
  latestRange?: { startTime: string; endTime: string }
  historyRange?: { startTime?: string; endTime: string }
  shouldCrawlHistory: boolean
}

/**
 * API响应格式
 */
interface ApiResponse<T = any> {
  success: boolean
  data?: T
  message?: string
  error?: {
    message: string
    code: string
  }
  timestamp: number
}

/**
 * 关键字窗口管理服务类
 */
export class KeywordWindowService {
  private static instance: KeywordWindowService

  private constructor() {}

  /**
   * 获取单例实例
   */
  static getInstance(): KeywordWindowService {
    if (!KeywordWindowService.instance) {
      KeywordWindowService.instance = new KeywordWindowService()
    }
    return KeywordWindowService.instance
  }

  /**
   * 获取所有关键字窗口
   */
  async getAllWindows(): Promise<KeywordWindowSummary[]> {
    try {
      const response = await ipcService.invoke<KeywordWindowSummary[]>(
        'keyword-window:get-all'
      )
      return response || []
    } catch (error) {
      logger.error('获取关键字窗口失败', error)
      throw error
    }
  }

  /**
   * 获取关键字窗口详情
   */
  async getKeywordWindow(keyword: string): Promise<KeywordWindowDetails> {
    try {
      const response = await ipcService.invoke<KeywordWindowDetails>(
        'keyword-window:get-details',
        keyword
      )
      
      if (!response) {
        throw new Error('未找到指定关键字的窗口')
      }
      return response
    } catch (error) {
      logger.error('获取关键字窗口详情失败', error)
      throw error
    }
  }

  /**
   * 更新关键字窗口设置
   */
  async updateKeywordWindow(
    keyword: string, 
    updates: KeywordWindowUpdateParams
  ): Promise<KeywordWindowSummary> {
    try {
      const response = await ipcService.invoke<KeywordWindowSummary>(
        'keyword-window:update',
        keyword,
        updates
      )
      
      if (!response) {
        throw new Error('更新失败，未返回数据')
      }
      
      return response
    } catch (error) {
      logger.error('更新关键字窗口设置失败', error)
      throw error
    }
  }

  /**
   * 重置关键字窗口
   */
  async resetKeywordWindow(keyword: string): Promise<KeywordWindowSummary> {
    try {
      const response = await ipcService.invoke<KeywordWindowSummary>(
        'keyword-window:reset',
        keyword
      )
      
      if (!response) {
        throw new Error('重置失败，未返回数据')
      }
      
      return response
    } catch (error) {
      logger.error('重置关键字窗口失败', error)
      throw error
    }
  }

  /**
   * 删除关键字窗口
   */
  async deleteKeywordWindow(keyword: string): Promise<void> {
    try {
      const response = await ipcService.invoke<void>(
        'keyword-window:delete',
        keyword
      )
      
      return response
    } catch (error) {
      logger.error('删除关键字窗口失败', error)
      throw error
    }
  }

  /**
   * 获取关键字的搜索时间范围
   */
  async getKeywordTimeRanges(keyword: string): Promise<TimeRanges> {
    try {
      const response = await ipcService.invoke<TimeRanges>(
        'keyword-window:get-time-ranges',
        keyword
      )
      
      if (!response) {
        throw new Error('获取时间范围失败，未返回数据')
      }
      
      return response
    } catch (error) {
      logger.error('获取关键字搜索时间范围失败', error)
      throw error
    }
  }

  /**
   * 获取需要历史爬取的关键字列表
   */
  async getKeywordsNeedingHistoryCrawl(interval?: number): Promise<{
    keywords: string[]
    total: number
    config: {
      historyCrawlInterval: number
      historyCrawlIntervalHours: number
    }
  }> {
    try {
      const response = await ipcService.invoke<{
        keywords: string[]
        total: number
        config: {
          historyCrawlInterval: number
          historyCrawlIntervalHours: number
        }
      }>(
        'keyword-window:get-history-crawl-needed',
        interval
      )
      
      
      if (!response) {
        logger.error('IPC返回成功但没有数据', { response })
        throw new Error('获取失败，未返回数据')
      }
      return response
    } catch (error) {
      logger.error('获取需要历史爬取的关键字列表失败', {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
        interval
      })
      throw error
    }
  }

  /**
   * 格式化时间显示
   */
  formatDateTime(date: Date | string | undefined): string {
    if (!date) return '未设置'
    
    const d = typeof date === 'string' ? new Date(date) : date
    if (isNaN(d.getTime())) return '无效日期'
    
    return d.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  /**
   * 格式化时间间隔显示
   */
  formatInterval(intervalMs: number): string {
    const hours = Math.floor(intervalMs / (1000 * 60 * 60))
    const days = Math.floor(hours / 24)

    if (days > 0) {
      return `${days}天${hours % 24}小时`
    } else {
      return `${hours}小时`
    }
  }

  /**
   * 验证关键字
   */
  validateKeyword(keyword: string): string {
    if (!keyword || keyword.trim() === '') {
      throw new Error('关键字不能为空')
    }
    
    const trimmed = keyword.trim()
    if (trimmed.length > 100) {
      throw new Error('关键字长度不能超过100个字符')
    }
    
    return trimmed
  }
}

/**
 * 全局关键字窗口服务实例
 */
export const keywordWindowService = KeywordWindowService.getInstance()
